/* 
 * File:   CServerSocket.h
 * Author: faraj
 *
 * Created on September 15, 2009, 2:39 AM
 */

#ifndef _CSERVERSOCKET_H
#define	_CSERVERSOCKET_H

#include "CWrapper.h"
#include "CSocket.h"

class CServerSocket
{
private:
    int sockfd;
    bool working;
    CInetAddress *address;
    
    
public:
    
    CServerSocket(int port)
    {
        sockaddr_in *addr = new sockaddr_in();

        this->sockfd = Socket(AF_INET,SOCK_STREAM,0);

        addr->sin_family = AF_INET;
        addr->sin_port = htons(port);
        addr->sin_addr.s_addr = htonl(INADDR_ANY);

        this->address = new CInetAddress(addr);
        
        working = Bind(this->sockfd,this->address->getSockaddr(),
                sizeof(*this->address->getSockaddr_in()));
        
        working &= Listen(this->sockfd,LISTENQ);
    }

    bool closeServerSocket()
    {
        return (close(this->sockfd) >= 0);
    }

    CSocket* accept()
    {
        sockaddr_in *cliaddr = new sockaddr_in();
        socklen_t len;
        len = sizeof(*cliaddr);
        int skfd = Accept(this->sockfd,(SA*)cliaddr,&len);

        CInetAddress *ciadd = new CInetAddress(cliaddr);

        return new CSocket(skfd,ciadd);
    }

    CInetAddress* getAddress()
    {
        this->address;
    }


};

#endif	/* _CSERVERSOCKET_H */

